﻿var UsersToDeleteArr = new Array();
function ChangePassword(UserID) {
    //            var NewPass = prompt("Введите новый пароль, все несохраненные данные будут потеряны", "");
    //            if (NewPass == "")
    //                alert("Пароль не может быть пустым");
    //            else {
    //                var newPass = document.getElementById("NewPass_" + UserID);
    //                newPass.setAttribute("value", NewPass);
    //            }
    //document.location.href = "sett.htm?command=ChangePassword&UserID=" + UserID + "&NewPass=" + NewPass;
    var div = document.getElementById("NewPassDiv_" + UserID);
    div.innerHTML = '<input type="text" id="NewPass_' + UserID + '" name="NewPass_"' + UserID + '" onchange="javascript:UserChanged(\'' + UserID + '\')"/>';
}

function UserChanged(UserID) {
    var UserChangedElement = document.getElementById("UserChanged_" + UserID);
    UserChangedElement.setAttribute("value", 1);
}

function Trim(str) {
    return str.replace(/^\s+/, '').replace(/\s+$/, '');
}

function RemoveIntRow(introwuid) {
    var Row = document.getElementById("introw" + introwuid);
    Row.parentNode.removeChild(Row);
}

function AddIntRow() {
    var Table = document.getElementById("inttable");
    var NewRowNumber = Math.ceil(Math.random() * 1000);
    var Row = Table.insertRow(-1);
    Row.setAttribute("id", "introw" + NewRowNumber);
    Row.setAttribute("style", "text-align:center");
    var Cell = Row.insertCell(-1);
    var input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "intip" + NewRowNumber);
    input.setAttribute("name", "intip" + NewRowNumber);
    input.setAttribute("size", 25);
    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "intname" + NewRowNumber);
    input.setAttribute("name", "intname" + NewRowNumber);
    input.setAttribute("size", 25);
    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    Cell.innerHTML = "<a href=\"javascript:RemoveIntRow('" + NewRowNumber + "')\"><img id=\"delete" + NewRowNumber + "\" name=\"delete" + NewRowNumber + "\" src=\"img/delete_g.png\" alt=\"Удалить строку\" onmouseover=\"javascript:ChangeImg('delete" + NewRowNumber + "', 7)\" onmouseout=\"javascript:ChangeImg('delete" + NewRowNumber + "', 6)\"></a>";
}

function ValidateUserForm() {

    var FailedVerify = new Array();

    var Elements = document.getElementsByTagName('input');
    for (var i = 0; i < Elements.length; i++) {
        var Element = Elements[i];
        if (Element.getAttribute('id') != null)
            if ((Element.getAttribute('id').indexOf('UserName_') != -1) ||
                    (Element.getAttribute('id').indexOf('UserFullName_') != -1) ||
                    (Element.getAttribute('id').indexOf('NewPass_') != -1)) {
                //alert(Element.getAttribute('id') + "\n" + Element.value);
                if (Trim(Element.value) == '') {
                    FailedVerify.push(Element.getAttribute('id'));
                }
            }
    }
    return FailedVerify;
}

function ValidateGeneralSettings() {
    var FailedVerify = new Array();
    var Element;
    Element = document.getElementById("sdffilename");
    if (Element.value = '')
        FailedVerify.push(Element.getAttribute('id'));
    return FailedVerify;

}

function ValidateSyslogSettings() {
    var FailedVerify = new Array();
    var Element;   
    Element = document.getElementById("syslogport");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("queueprocessingperiod");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("cachescount");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("cachesize");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("flushperiod");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("dnsresolve");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("dnsresolvetimeout");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));

    var Elements = document.getElementsByTagName('input');
    for (var i = 0; i < Elements.length; i++) {
        var IntElement = Elements[i];
        if (IntElement.getAttribute('id') != null)
            if ((IntElement.getAttribute('id').indexOf('intip') != -1) || (IntElement.getAttribute('id').indexOf('intname') != -1))
                if (IntElement.value == '')
                    FailedVerify.push(IntElement.getAttribute('id'));
    }
    return FailedVerify;

}

function ValidateWebserverSettings() {
    var FailedVerify = new Array();
    var Element;
    Element = document.getElementById("webport");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("sessiontimeout");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("tempdirclear");
    if (isNaN(Element.value - 0))
        FailedVerify.push(Element.getAttribute('id'));
    Element = document.getElementById("wwwpath");
    if (Element.value == '')
        FailedVerify.push(Element.getAttribute('id'));
   
    return FailedVerify;

}

function ClearErrorMarking() {
    var Elements = document.getElementsByTagName('input');
    for (var i = 0; i < Elements.length; i++) {
        var isTextBox = Elements[i].getAttribute("type");
        if ((isTextBox != null) && (isTextBox != undefined) && (isTextBox == 'text'))
        Elements[i].setAttribute("class", "clearfield");
    }
}

function SaveUsersData() {
    ClearErrorMarking();
    var VerifyResult = ValidateUserForm();
    if (VerifyResult.length != 0) {
        for (var i = 0; i < VerifyResult.length; i++) {
            var Element = document.getElementById(VerifyResult[i]);
            Element.setAttribute("class", "errorfield");
        }
        alert("Найдены ошибки в полях");
        return;
    }
    //params for delete
    var deleteparam = '';
    if (UsersToDeleteArr.length > 0) {
        for (var i = 0; i < UsersToDeleteArr.length; i++) {
            deleteparam += "&deleteuser_" + i + "=" + UsersToDeleteArr[i];
        }
        deleteparam += "&deleteusercount=" + UsersToDeleteArr.length;
    }
    //params for insert or update
    var params = '';
    var ChangedUsers = new Array();
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        var ID = inputs[i].getAttribute("id");
        if (ID != null) {
            if (ID.indexOf("UserChanged_") != -1) {
                if (inputs[i].value == 1)
                    ChangedUsers.push(ID.split('_')[1]);
            }
        }
    }
    if ((ChangedUsers.length == 0) && (UsersToDeleteArr.length == 0)) {
        alert("Не было изменений");
        return;
    }
    for (var i = 0; i < ChangedUsers.length; i++) {
        var ID = ChangedUsers[i];
        params += "&UserID_" + i + "=" + ID;
        params += "&UserName_" + i + "=" + document.getElementById("UserName_" + ID).value;
        params += "&UserFullName_" + i + "=" + document.getElementById("UserFullName_" + ID).value;
        params += "&UserAccessLevel_" + i + "=" + document.getElementById("UserAccessLevel_" + ID).value;
        params += "&UserIPAddress_" + i + "=" + document.getElementById("UserIPAddress_" + ID).value;
        var NewPass = document.getElementById("NewPass_" + ID);
        if (NewPass != null)
            params += "&NewPass_" + i + "=" + NewPass.value;
    }

    //    var params2 = '';
    //    var selects = document.getElementsByTagName('select');
    //    var Elements = new Array();
    //    for (var i = 0; i < inputs.length; i++)
    //        Elements.push(inputs[i]);
    //    for (var i = 0; i < selects.length; i++)
    //        Elements.push(selects[i]);
    //    for (var i = 0; i < Elements.length; i++) {
    //        var ID = Elements[i].getAttribute("id");
    //        if (ID != null)
    //        params2 += "&" + ID + "=" + Elements[i].value;
    //    }
    //    alert(params);
    //    alert(params.length);
    //    alert(params2);
    //    alert(params2.length);
    //    return;
    document.getElementById("UserSettTab").innerHTML = '<img src="img/waiting.gif" alt="Сохранение..."/>';
    var url = "userssett.wcmd?action=userssave&UsersCount=" + ChangedUsers.length + params + deleteparam;
    SendRequestAsync(url, saveuserscallback, null, null);
}

function SelectAllRows() {
    var Value = document.getElementById('SelectAll').checked;
    var Elements = document.getElementsByTagName('input');
    for (var i = 0; i < Elements.length; i++) {
        var Element = Elements[i];
        if ((Element.getAttribute('type') == 'checkbox') && (Element.getAttribute('id').indexOf('UserToDelete_') != -1))
            Element.checked = Value;
    }
}

//        function UpdateDebugInfo() {

//            var Elements = document.getElementsByTagName('input');
//            var Rows = 0;
//            for (var i = 0; i < Elements.length; i++) {
//                var Element = Elements[i];
//                if ((Element.getAttribute('type') == 'text') && (Element.getAttribute('id').indexOf('UserName_') != -1))
//                    Rows++;
//            }
//            var Div = document.getElementById("debug");
//            Div.innerHTML = "Rows: " + Rows;

//        }

function AddRow() {
    var NewRowNumber = Math.ceil(Math.random() * 1000);
    var UserTable = document.getElementById("UserTable");
    var Row = UserTable.insertRow(-1);
    Row.setAttribute("id", "Row_" + NewRowNumber);
    Row.setAttribute("style", "text-align:center");
    var Cell = Row.insertCell(-1);
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("id", "UserChanged_" + NewRowNumber);
    input.setAttribute("name", "UserChanged_" + NewRowNumber);
    input.setAttribute("value", 0);
    Cell.appendChild(input);
    input = document.createElement("input");
    input.setAttribute("type", "checkbox");
    input.setAttribute("id", "UserToDelete_" + NewRowNumber);
    input.setAttribute("name", "UserToDelete_" + NewRowNumber);
    input.checked = false;
    Cell.appendChild(input);
    input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("id", "OrigUserAccessLevel_" + NewRowNumber);
    input.setAttribute("name", "OrigUserAccessLevel_" + NewRowNumber);
    input.setAttribute("value", '');
    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "UserName_" + NewRowNumber);
    input.setAttribute("name", "UserName_" + NewRowNumber);
    input.setAttribute("onchange", "javascript:UserChanged('" + NewRowNumber + "')");
    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "UserFullName_" + NewRowNumber);
    input.setAttribute("name", "UserFullName_" + NewRowNumber);
    input.setAttribute("onchange", "javascript:UserChanged('" + NewRowNumber + "')");
    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    input = document.createElement("select");
    input.setAttribute("id", "UserAccessLevel_" + NewRowNumber);
    input.setAttribute("name", "UserAccessLevel_" + NewRowNumber);
    input.setAttribute("onchange", "javascript:UserChanged('" + NewRowNumber + "')");

    var Elements = document.getElementsByTagName('select');
    for (var i = 0; i < Elements.length; i++) {
        var Element = Elements[i];
        if (Element.getAttribute("id").indexOf("UserAccessLevel_") != -1)
        // input.options = Element.options;
            for (k = 0; k < Element.options.length; k++) {
                var NewOption = document.createElement("option");
                //NewOption.setAttribute("value",Element.options[k].value);
                NewOption.value = Element.options[k].value;
                NewOption.text = Element.options[k].text;
                input.options.add(NewOption);
            }
        break;
    }

    Cell.appendChild(input);
    Cell = Row.insertCell(-1);
    input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "UserIPAddress_" + NewRowNumber);
    input.setAttribute("name", "UserIPAddress_" + NewRowNumber);
    input.setAttribute("onchange", "javascript:UserChanged('" + NewRowNumber + "')");
    Cell.appendChild(input);
    //    try {
    //        $("#UserIPAddress_" + NewRowNumber).autocomplete("autocompleteaddress.wcmd", {
    //            delay: 400,
    //            minChars: 3,
    //            matchSubset: false,
    //            autoFill: true,
    //            matchContains: false,
    //            cacheLength: 1,
    //            selectFirst: true,
    //            formatItem: liFormat,
    //            max: 20,
    //            onItemSelect: selectItem,
    //            scroll: true
    //        });
    //    }
    //    catch (e) {
    //        alert(e);
    //    }
    //Cell.innerText = Script;
    //alert(Cell.innerText);
    Cell = Row.insertCell(-1);
    input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("id", "NewPass_" + NewRowNumber);
    input.setAttribute("name", "NewPass_" + NewRowNumber);
    input.setAttribute("onchange", "javascript:UserChanged('" + NewRowNumber + "')");
    Cell.appendChild(input);
    //Cell = Row.insertCell(-1);
    //UpdateDebugInfo();
}

function RemoveRows() {
    var Elements = document.getElementsByTagName('input');
    var i = 0;
    while (i < Elements.length) {
        var Element = Elements[i];
        if ((Element.getAttribute('type') == 'checkbox') && (Element.getAttribute('id').indexOf('UserToDelete_') != -1) && (Element.checked)) {
            var ID = Element.getAttribute('id').split('_')[1];
            var Row = document.getElementById("Row_" + ID);
            if (document.getElementById("OrigUserAccessLevel_" + ID).value != "Суперадмин") {
                Row.parentNode.removeChild(Row);
                if (ID.length == 36)
                    UsersToDeleteArr.push(ID);
                i--;
            }
            else {
                alert("Суперадминистратор не может быть удален");
            }
            //var UserTable = document.getElementById("UserTable");
            //UserTable.deleteRow(Row);                    
            //Row.setAttribute("style", "background-color:#FFAAAA");
        }
        i++;

    }
    //UpdateDebugInfo();
}

function ChangeImg(imgname, imgnum) {
    document.getElementById(imgname).src = Images[imgnum].src;
}


function savegeneralsett() {
    ClearErrorMarking();
    var VerifyResult = ValidateGeneralSettings();
    if (VerifyResult.length != 0) {
        for (var i = 0; i < VerifyResult.length; i++) {
            var ErrElement = document.getElementById(VerifyResult[i]);
            ErrElement.setAttribute("class", "errorfield");
        }
        alert("Найдены ошибки в полях");
        return;
    }

    var url = "generalsett.wcmd?action=generalsettsave&sdffilename=" + document.getElementById("sdffilename").value;
    document.getElementById("GeneralSettTab").innerHTML = '<img src="img/waiting.gif" alt="Сохранение..."/>';
    SendRequestAsync(url, savegeneralsettcallback, null, null);
    
    alert("Для применения настроек необходимо перезапустить сервис");
}

function savesyslogsett() {
    ClearErrorMarking();
    var VerifyResult = ValidateSyslogSettings();
    if (VerifyResult.length != 0) {
        for (var i = 0; i < VerifyResult.length; i++) {
            var ErrElement = document.getElementById(VerifyResult[i]);
            ErrElement.setAttribute("class", "errorfield");
        }
        alert("Найдены ошибки в полях");
        return;
    }
    var url = "syslogsett.wcmd?action=syslogsettsave";
    url += "&port=" + document.getElementById("syslogport").value;
    url += "&queueprocessingperiod=" + document.getElementById("queueprocessingperiod").value;
    url += "&cachescount=" + document.getElementById("cachescount").value;
    url += "&cachesize=" + document.getElementById("cachesize").value;
    url += "&flushperiod=" + document.getElementById("flushperiod").value;
    url += "&dnsresolve=" + document.getElementById("dnsresolve").value;
    url += "&dnsresolvetimeout=" + document.getElementById("dnsresolvetimeout").value;
    var Elements = document.getElementsByTagName('input');
    for (var i = 0; i < Elements.length; i++) {
        var Element = Elements[i];
        if (Element.getAttribute('id') != null)
            if ((Element.getAttribute('id').indexOf('intip') != -1) || (Element.getAttribute('id').indexOf('intname') != -1))
                url += "&" + Element.getAttribute('id') + "=" + Element.value;
    }

    document.getElementById("SyslogSettTab").innerHTML = '<img src="img/waiting.gif" alt="Сохранение..."/>';
    SendRequestAsync(url, savesyslogsettcallback, null, null);

    alert("Для применения настроек необходимо перезапустить сервис");

}

function savewebserversett() {
    ClearErrorMarking();
    var VerifyResult = ValidateWebserverSettings();
    if (VerifyResult.length != 0) {
        for (var i = 0; i < VerifyResult.length; i++) {
            var ErrElement = document.getElementById(VerifyResult[i]);
            ErrElement.setAttribute("class", "errorfield");
        }
        alert("Найдены ошибки в полях");
        return;
    }
    var url = "webserversett.wcmd?action=webserversettsave";
    url += "&webport=" + document.getElementById("webport").value;
    url += "&sessiontimeout=" + document.getElementById("sessiontimeout").value;
    url += "&tempdirclear=" + document.getElementById("tempdirclear").value;
    url += "&wwwpath=" + document.getElementById("wwwpath").value;
    document.getElementById("WebSettTab").innerHTML = ' <img src="img/waiting.gif" alt="Сохранение..."/>';
    SendRequestAsync(url, savewebserversettcallback, null, null);

    alert("Для применения настроек необходимо перезапустить сервис");
}


try {
    jQuery(function ($) {
        $.datepicker.regional['ru'] = {
            closeText: 'Закрыть',
            prevText: '&#x3c;Пред',
            nextText: 'След&#x3e;',
            currentText: 'Сегодня',
            monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
		'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
            monthNamesShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн',
		'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
            dayNames: ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'],
            dayNamesShort: ['вск', 'пнд', 'втр', 'срд', 'чтв', 'птн', 'сбт'],
            dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
            weekHeader: 'Нед',
            dateFormat: 'dd.mm.yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };
        $.datepicker.setDefaults($.datepicker.regional['ru']);
    });
}
catch (e)
    { }

$(function () {


    $("#PeriodStart").datepicker({
        changeMonth: true,
        changeYear: true,
        showOtherMonths: true
    });

    $("#PeriodEnd").datepicker({
        changeMonth: true,
        changeYear: true,
        showOtherMonths: true
    });

    $("#PeriodStartByUser").datepicker({
        changeMonth: true,
        changeYear: true,
        showOtherMonths: true
    });

    $("#PeriodEndByUser").datepicker({
        changeMonth: true,
        changeYear: true,
        showOtherMonths: true
    });

    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(
					function () { $(this).addClass('ui-state-hover'); },
					function () { $(this).removeClass('ui-state-hover'); }
				);

    // Tabs
    $('#ReportTabs').tabs();
    $('#SettingsTabs').tabs();
    $('#MainSettTabs').tabs();

}
        );


function ChangePeriodEnable() {
    PeriodStart.disabled = !PeriodStart.disabled;
    PeriodEnd.disabled = !PeriodEnd.disabled;
}
function ChangeUserEnable() {
    UserID.disabled = !UserID.disabled;
}
function ChangeSrcEnable() {
    SrcAddress.disabled = !SrcAddress.disabled;
}
function ChangeDstEnable() {
    DstAddress.disabled = !DstAddress.disabled;
}

function param_list() {
    var aparam_list = new Array();
    var url = document.location.href;
    var paramstring = url.split("?")[1];
    if (paramstring != null) {
        var params = paramstring.split["&"];
        if (params.length > 0) {
            for (var i = 0; i < params.length; i++) {
                var paramdata = params[i].split("=");
                aparam_list[paramdata[0]] = paramdata[1];
            }
        }
    }
    return aparam_list;
}

//function FillReportFormFields() {
//    var Params = param_list();
//    if (Params.length > 0) {
//        if (Params["periodenable"] != null)
//            PeriodEnable.checked = (Params["periodenable"] == "on");
//        if (Params["periodstart"] != null)
//            PeriodStart.value = Params["periodstart"];
//        if (Params["periodend"] != null)
//            PeriodEnd.value = Params["periodend"];
//        if (Params["userenable"] != null)
//            UserEnable.checked = (Params["userenable"] == "on");
//        if (Params["userid"] != null)
//            UserID.value = Params["userid"];
//        if (Params["srcenable"] != null)
//            SrcEnable.checked = (Params["srcenable"] == "on");
//        if (Params["srcaddress"] != null)
//            SrcAddress.value = Params["srcaddress"];
//        if (Params["dstenable"] != null)
//            DstEnable.checked = (Params["dstenable"] == "on");
//        if (Params["dstaddress"] != null)
//            DstAddress.value = Params["dstaddress"];  
//    }
//}